<template>
  <view class="uv-page" style="background-color: #fff;">
    <view class="uv-demo-block">
      <view class="uv-demo-block__content">
        <uv-form :model="form" :rules="rules" ref="form1" labelWidth="auto">
          <uv-form-item prop="userName" required label="用户:" borderBottom @click="showUserSelect">
            <uv-input v-model="form.userName" disabled disabledColor="#ffffff" placeholder="请选择用户"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="declareDate" required label="日期:" borderBottom @click="declareDateOpen">
            <uv-input v-model="form.declareDate" disabled disabledColor="#ffffff" placeholder="请选择日期"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="areaName"  label="区域:" borderBottom @click="showAreaSelect">
            <uv-input v-model="form.areaName" disabled disabledColor="#ffffff" placeholder="请选择区域"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="itemType" label="物品类型:" borderBottom @click="showTypeSelect">
            <uv-input v-model="itemTypeLabel" disabled disabledColor="#ffffff" placeholder="请选择物品类型"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="itemName" required label="说明:" borderBottom labelPosition="top">
            <uv-textarea v-model="form.itemName" placeholder="请输入说明"></uv-textarea>
          </uv-form-item>
          <uv-form-item prop="remark" label="备注:" borderBottom labelPosition="top">
            <uv-textarea v-model="form.remark" placeholder="请输入备注"></uv-textarea>
          </uv-form-item>
          <uv-form-item prop="enclosure" label="附件:" borderBottom>
            <view style="display: flex;align-items: flex-start;">
              <uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
                         :uploadText="pictureText" @delete="deletePic" :disabled="pictureDisabled"
                         width="80" :deletable="!pictureDisabled" height="80"></uv-upload>
            </view>
          </uv-form-item>

        </uv-form>

        <uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="openSubmitModal"></uv-button>

        <!--  提交确认弹窗  -->
        <uv-modal ref="submitModal" title="提交确认" content='提交后将无法修改，您确定要提交吗？' @confirm="submit"
                  align="center"
                  :showCancelButton="true"></uv-modal>

        <!-- 选择填单日期 -->
        <uv-datetime-picker ref="declareDatePicker" v-model="declareDate" mode="date"
                            @confirm="declareDateConfirm"></uv-datetime-picker>
        <!-- 选择用户 -->
        <uv-picker ref="userSelectPicker"
                   :columns="userData"
                   @confirm="userSelect"
                   @cancel="userCancel"
                   keyName="realName"></uv-picker>

        <!-- 选择区域 -->
        <uv-picker ref="areaSelectPicker"
                   :columns="areaData"
                   @confirm="areaSelect"
                   @cancel="areaCancel"
                   keyName="title"></uv-picker>

        <!-- 选择区域 -->
        <uv-picker ref="typeSelectPicker"
                   :columns="itemTypeData"
                   @confirm="typeSelect"
                   @cancel="typeCancel"
                   keyName="dictValue"></uv-picker>
      </view>
    </view>
  </view>
</template>
<script>

import CommonAPI from '@/api/common'
import UploadAPI from '@/api/upload'
import ReportedLossAPI from '@/api/reportedloss'
import AreaAPI from "@/api/area";
import DictAPI from "@/api/dict";
import {timeFormat} from "@climblee/uv-ui/libs/function";

export default {
  data() {
    return {
      declareDate: Number(new Date()), //填单日期
      itemTypeLabel: '',
      userData: [], // 待选用户列表
      areaData: [], // 待选区域列表
      itemTypeData:[], // 待选物品类型列表
      form: {
        enclosure: '',
        itemType: '',
        itemName: '',
        createTime: '',
        userName: '',
        areaName: '',
        declareDate: ''
      },

      rules: {
        itemName: {
          required: true,
          message: '请输入明细',
          trigger: ['blur']
        },
        userName: {
          required: true,
          message: '请输入用户',
          trigger: ['blur']
        },
        areaName:{
          required: false,
          message: '请输入区域',
          trigger: ['blur']
        }
      },
      fileList1: [], // 上传的附件
      pictureDisabled: false,
      pictureText: '',
    }
  },

  onReady() {
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.form1.setRules(this.rules)
  },
  onLoad() {
    this.init()
  },
  methods: {
    openSubmitModal() {
      this.$refs.submitModal.open();
    },
    declareDateOpen() {
      this.$refs.declareDatePicker.open();
    },
    declareDateConfirm(e) {
      console.info(e)
      this.form.declareDate = timeFormat(e.value, 'yyyy-mm-dd')
    },

    // 用户选择
    showUserSelect() {
      this.$refs.userSelectPicker.open();
    },
    userSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.userId = element.id
      this.form.userName = element.realName
    },
    userCancel() {
      this.form.userId = ''
      this.form.userName = ''
    },

    // 区域选择
    showAreaSelect() {
      this.$refs.areaSelectPicker.open();
    },
    areaSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.areaId = element.id
      this.form.areaName = element.title
    },
    areaCancel() {
      this.form.areaId = ''
      this.form.areaName = ''
    },

    // 物品类型选择
    showTypeSelect() {
      this.$refs.typeSelectPicker.open();
    },
    typeSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.itemType = element.dictKey
      this.itemTypeLabel = element.dictValue
    },
    typeCancel() {
      this.itemTypeLabel= ''
      this.form.itemType = ''
    },

    init() {
      CommonAPI.userAttendance().then(res => {
        if (res.code !== 200) {
          return
        }
        this.userData = [[...res.data]]
      })

      AreaAPI.tree(1).then(res => {
        if (res.code !== 200) {
          return
        }
        this.areaData = [
          [...res.data]
        ]
      })
      DictAPI.dictByCodeList({code: 'item_type'}).then(res => {
        this.itemTypeData = [[...res.data]]
      })
    },
    // 提交
    submit() {
      this.form.enclosure = this.fileList1.map(i => i.url).join(',')
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form1.validate().then(res => {
        ReportedLossAPI.reportedLossSubmit(this.form).then(res => {
          if (res.code === 200) {
            uni.showToast({
              icon: 'success',
              title: '提交成功'
            })
          }
          // 返回首页
          uni.navigateTo({
            url: '/subpackage/reportedloss/reportedloss'
          })
        })
      }).catch(errors => {
        uni.showToast({
          icon: 'error',
          title: '校验失败'
        })
      })
    },
    typeChange(e) {
      console.info(e)
      this.form.type = e
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.info(event)
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    async uploadFilePromise(url) {
      let data = await UploadAPI.uploadFile(url)
      return data.link
    }
  }
}
</script>
<style lang="scss" scoped>
.uv-page {
  padding: 15px 15px 40px 15px;
}

.uv-demo-block {
  margin-bottom: 22px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__content {
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;
}

.uv-page__tag-item {
  margin-right: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  margin: 1px; /* 根据需要调整间距 */
}
</style>